import {promptBox, base, toast} from 'nc-lightapp-front';
import addTemplate from "./addTemplate";
import getSysConf from "../../../public/functions/getSysConf";
import {formatDate} from "../../../../hrpub/common/utils/utils";
import {getSignStatus} from "./commonFun";

export default class MainAction {

    constructor(comp) {
        this.comp = comp;
    }

    getClientHeight = () => {
        let {width} = document.querySelector('#app').getBoundingClientRect()
        let height = document.documentElement.clientHeight - 200;
        width = width - 256;
        this.comp.props.dispatch({
            type: 'myLeave/update',
            payload: {
                clientHeight: height,
                clientWidth: width
            }
        })
    }

    getTempalte = () => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/languageCreateUIDOM',
            payload: {
                ...this.comp.props,
                callback: this.initailMeta
            }
        })
    }
    getLangCode = (sName) => {
        var sRE = "(?:; )?" + sName + "=([^;]*);?";
        var oRE = new RegExp(sRE);
        if (oRE.test(document.cookie)) {
            return RegExp["$1"];
        }
        return null;
    }

    addOperateCol = (template, buttons) => {

        const {myLeave, button} = this.comp.props;
        let langCode = this.getLangCode('langCode');
        let oprWidth = '180px'
        if (langCode === 'english') {
            oprWidth = '270px'
        }

        let render1 = (text, record, index) => {
            let edit = record.values.approvestatus
                && record.values.approvestatus.value === '-1'
            let recall = record.values.approvestatus
                && record.values.approvestatus.value === '3'

            let listBtns = []
            buttons.forEach(btn => {
                if (btn.area === 'list') {
                    if ((btn.key === 'list_submit' || btn.key === 'list_edit'
                        || btn.key === 'list_del') && !edit) {
                        return
                    }
                    if (btn.key === 'list_withdraw' && !recall) {
                        return
                    }
                    listBtns.push(btn.key)
                }
            })

            return (
                <div className="currency-opr-col">
                    {button.createOprationButton(listBtns,
                        {
                            area: 'list',
                            buttonLimit: 2,
                            onButtonClick: (props, id, e) => {
                                this.listClickHandle(id, record)
                            }
                        }
                    )}
                </div>
            );
        }

        template['attendance_list'].items.push({
            attrcode: 'operation',
            renderStatus: 'browse',
            itemtype: 'customer',
            label: myLeave.json['6040-000019'], /* 国际化处理： 操作*/
            width: oprWidth,
            visible: true,
            fixed: 'right',
            render: render1
        })
    }

    listClickHandle = (key, record) => {
        if (key === 'list_flow') {
            this.showFlowHistory(record, 1)
        } else if (key === 'list_withdraw') {
            this.recallBill(record)
        } else if (key === 'list_submit') {
            this.submitBill(record)
        } else if (key === 'list_file') {
            this.showUploader(record);
        } else if (key === 'list_edit') {
            this.editBill(record);
        } else if (key === 'list_del') {
            this.deleteBill(record, 'leave');
        }
    }

    initailMeta = (metas, lang, intl) => {
        let {button, template} = metas;
        const props = this.comp.props;
        const {renderItem, meta, dispatch} = props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                json: lang
            }
        })
        this.addOperateCol(template, button);
        addTemplate(template, lang)
        this.handleMeta(template, renderItem)
        meta.setMeta(template ? template : {});
        props.button.setButtons(button);
        dispatch({
            type: 'myLeave/update',
            payload: {
                templateInited: true
            }
        })
    }

    handleMeta = (template) => {
        template['attendance_card'].items.forEach(item => {
            if (item.attrcode === 'transtypeid') {
                if (!item.queryCondition) {
                    item.queryCondition = {
                        GridRefActionExt: "nccloud.web.hrkq.attendance.sqlbuilder.AttendTransTypeRefSqlBuilder"
                    }
                } else {
                    item.queryCondition = Object.assign(item.queryCondition, {
                        GridRefActionExt: "nccloud.web.hrkq.attendance.sqlbuilder.AttendTransTypeRefSqlBuilder"
                    })
                }
            } else if (item.attrcode === "pk_attend_staff") {
                if (!item.queryCondition) {
                    item.queryCondition = {}
                }
                item.queryCondition = Object.assign(item.queryCondition, {
                    isSingle: "1"
                })
            }
        })
    }

    submitBill = (record) => {
        const {dispatch, myLeave} = this.comp.props;
        const key = 'attendance'
        dispatch({
            type: 'myLeave/submitBillAction',
            payload: {
                key,
                pk: record.values['pk_' + key].value
            }
        }).then(res => {
            if (res.success) {
                if (res.data && res.data.content) {
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            assignedData: res.data.content,
                            assignedDisplay: true
                        }
                    })
                } else {
                    toast({
                        color: 'success',
                        content: myLeave.json['6040-00004']  // 提交成功！
                    });
                    this.queryListAction();
                }
            }
        })
    }

    showUploader = (record) => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                showUploader: true,
                billId: record.values['pk_attendance'].value,
                approvestatus: record.values['approvestatus'].value,
            }
        })
    }

    editBill = (record) => {
        const {dispatch, myLeave, form, editTable} = this.comp.props;
        const {json = {}} = myLeave;
        let minTime = '';
        let formCode = myLeave.activeTab + '_card';
        const {setFormStatus, setAllFormValue, setItemsVisible, EmptyAllFormValue, setFormItemsRequired} = form;
        EmptyAllFormValue(formCode);
        setFormStatus(formCode, 'edit');
        editTable.setStatus('batch_attend_edit_list', 'edit')
        let cardDefaultVisiable = {
            fill_date: false,
            original_sign_status: false,
            original_sign_time: false,
            fill_time: false
        }
        let cardDefaultRequired = {
            fill_type_id: true
        }
        setItemsVisible(formCode, cardDefaultVisiable);
        setFormItemsRequired(formCode, cardDefaultRequired);
        setAllFormValue({
            [formCode]: {
                rows: [record]
            }
        })
        let batch_attend_list = {
            areacode: 'batch_attend_edit_list',
            rows: []
        }
        let isFreeAdd = true;
        if (record.values.fill_details
            && record.values.fill_details.value) {
            let tempData = JSON.parse(record.values.fill_details.value)
            tempData.forEach((item, index) => {
                if (item['originalSignStatus']) {
                    isFreeAdd = false
                }
                let values = {
                    fillDate: {
                        value: typeof item['fillDate'] === 'number' ? formatDate(item['fillDate']): item['fillDate']
                    },
                    fillTime: {
                        value: typeof item['fillTime'] === 'number' ? formatDate(item['fillTime'], ':', 'hh-mm'): item['fillTime'].substring(0,5)
                    },
                    originalSignTime: {
                        value: item['fillTime']
                    },
                    listOrder: {
                        value: item['originalSignTime'] ? formatDate(item['originalSignTime'], ' ', 'y-m-d-h-m'): ''
                    },
                    isNeedFill: {
                        value: ''
                    },
                    signState: {
                        value: item['originalSignStatus'],
                        display: getSignStatus(item['originalSignStatus'], json)
                    },
                    originalSignStatus: {
                        value: item['originalSignState']
                    },
                    fillStatus: {
                        value: ''
                    },
                    fill_reason: {
                        value: item['fill_reason']
                    }
                };
                batch_attend_list.rows.push({
                    status: '0',
                    values
                })
            })
        }
        editTable.setTableData('batch_attend_edit_list', batch_attend_list);
        dispatch({
            type: 'myLeave/update',
            payload: {
                showMode: 'card',
                isEdit: true,
                isFreeAdd,
                minTime,
                billId: record.values['pk_' + myLeave.activeTab].value,
                headerTitle: myLeave.subTitle,
                approvestatus: record.values['approvestatus'] && record.values['approvestatus'].value
            }
        })
    }


    /**
     * @desc:
     * @param {type}
     * @return:
     */
    showFlowHistory = (record, type) => {
        const {dispatch, myLeave} = this.comp.props;
        let billId
        let billtype
        billtype = record.values['billtype'].value
        billId = record.values['pk_' + myLeave.activeTab].value;
        billtype = (record.values['transtype'] && record.values['transtype'].value) || billtype
        dispatch({
            type: 'myLeave/update',
            payload: {
                showApproveDetail: true,
                billId,
                billtype
            }
        })
    }

    /**
     * @desc: 单据撤回操作
     * @param {type}
     * @return:
     */
    recallBill = (record) => {
        const {dispatch, myLeave, editTable} = this.comp.props;
        let pk = record.values['pk_' + myLeave.activeTab].value;
        let tableCode = myLeave.activeTab + '_list';
        let activeTab = myLeave.activeTab
        let status = record.values.approvestatus.value;
        let revokestatus = record.values.approvestatus.value === '1' && (record.values.tripoffapprovestatus && record.values.tripoffapprovestatus.value || record.values.leaveoffapprovestatus && record.values.leaveoffapprovestatus.value)
        if (status === '1' && revokestatus === '3') {
            pk = record.values['pk_' + myLeave.activeTab + 'off'].value;
            activeTab = myLeave.activeTab + 'off'
        }
        promptBox({
            color: "warning",
            title: myLeave.json['6040-00005'], /* 国际化处理： 提示*/
            content: myLeave.json['6040-000023'], /* 国际化处理： 你确定要撤回该单据吗？*/
            beSureBtnClick: () => {
                dispatch({
                    type: 'myLeave/recallAction',
                    payload: {
                        key: activeTab,
                        pk
                    }
                }).then(res => {
                    if (res.success) {
                        toast({
                            color: 'success',
                            content: myLeave.json['6040-000024']
                        });
                        dispatch({
                            type: 'myLeave/queryListAction',
                            payload: {
                                key: myLeave.activeTab,
                                beginDate: myLeave.beginValue,
                                endDate: myLeave.endValue
                            }
                        }).then(res => {
                            if (res.success) {
                                if (res.data) {
                                    editTable.setTableData(tableCode, res.data[tableCode])
                                    dispatch({
                                        type: 'myLeave/update',
                                        payload: {
                                            [myLeave.activeTab + 'PageInfo']: res.data[tableCode].pageInfo
                                        }
                                    })
                                }
                            }
                        })
                    }
                })
            }
        })
    }

    deleteBill = (record) => {
        const {dispatch, myLeave} = this.comp.props;
        let billId = record.values['pk_' + myLeave.activeTab].value;
        promptBox({
            color: "warning",
            title: myLeave.json['6040-00005'], /* 国际化处理： 提示*/
            content: myLeave.json['6040-000060'],
            beSureBtnClick: () => {
                dispatch({
                    type: 'myLeave/deleteAction',
                    payload: {
                        activeTab: myLeave.activeTab,
                        pk: billId
                    }
                }).then(res => {
                    if (res.success) {
                        toast({
                            color: 'success',
                            content: myLeave.json['6040-000012']
                        })
                        this.queryListAction();
                    }
                })
            }
        })
    }

    closeApproveDetailDialog = () => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                showApproveDetail: false
            }
        })
    }
    handlePageIndexChange = (pageIndex) => {
        const {dispatch, myLeave} = this.comp.props
        let pageInfo = myLeave.activeTab + 'PageInfo'
        dispatch({
            type: 'myLeave/update',
            payload: {
                [pageInfo]: Object.assign({}, myLeave[pageInfo], {
                    pageIndex
                })
            }
        })
        this.queryListAction()
    }

    queryListAction = () => {
        const {dispatch, myLeave, editTable} = this.comp.props;
        const {beginValue, endValue} = myLeave;
        let tableCode = myLeave.activeTab + '_list';
        dispatch({
            type: 'myLeave/queryListAction',
            payload: {
                key: myLeave.activeTab,
                beginDate: beginValue,
                endDate: endValue
            }
        }).then(res => {
            if (res.success) {
                if (res.data) {
                    editTable.setTableData(tableCode, res.data[tableCode]);
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            [myLeave.activeTab + 'PageInfo']: res.data[tableCode].pageInfo
                        }
                    })
                } else {
                    editTable.setTableData(tableCode, {rows: []});
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            [myLeave.activeTab + 'PageInfo']: Object.assign({}, myLeave[myLeave.activeTab + 'PageInfo'], {total: null})
                        }
                    })
                }
            }
        })
    }

    didMount = () => {
        if (window.location.href.match(/(localhost|127\.0\.0\.1)/)) {
            window.location.hash = `#ifr?page=2019916105952100`;
        }
        this.getClientHeight()
        this.getSysConf();
        this.getTempalte()
    }

    getSysConf = async () => {
        const {myLeave, dispatch} = this.comp.props;
        const {attendancePageInfo} = myLeave
        let pageSize = await getSysConf();

        dispatch({
            type: 'myLeave/update',
            payload: {
                attendancePageInfo: {
                    ...attendancePageInfo,
                    pageSize: pageSize
                }
            }
        })
    }
}